package com.dotstone.chipism.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.FragmentAdapter;
import com.dotstone.chipism.adapter.WlanHorizonAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.DeviceVersion;
import com.dotstone.chipism.bean.ExpandableLayout;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Key;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.MySocket.RecDataCallBackListener_Update;
import com.dotstone.chipism.bean.Order;
import com.dotstone.chipism.bean.Version;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.fragment.MainFragment;
import com.dotstone.chipism.listener.AppVersionListener;
import com.dotstone.chipism.listener.DeviceVersionListener;
import com.dotstone.chipism.listener.OnExtrusionListener;
import com.dotstone.chipism.listener.OnOperItemClickL;
import com.dotstone.chipism.listener.UpdateDataListener;
import com.dotstone.chipism.ui.curtain.RemoteCurtainActivity;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.ui.security.dialog.DialogWaitting;
import com.dotstone.chipism.ui.security.me.DeviceCameraMainActivity;
import com.dotstone.chipism.util.CancelException;
import com.dotstone.chipism.util.CheckStatusUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.KeyManager;
import com.dotstone.chipism.util.MyDBHelper;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.SocketManager.OrderListener;
import com.dotstone.chipism.util.StatusBarHeightManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.BlurBehind;
import com.dotstone.chipism.view.CustomViewPager;
import com.dotstone.chipism.view.EditDeviceNameDialog;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.NormalListDialog;
import com.dotstone.chipism.view.OnBlurCompleteListener;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.dotstone.chipism.view.slidingfragmenu.SlidingFragmentActivity;
import com.dotstone.chipism.view.slidingfragmenu.SlidingMenu;
import com.dotstone.chipism.view.slidingfragmenu.SlidingMenu.OnCloseListener;
import com.dotstone.chipism.view.slidingfragmenu.SlidingMenu.OnOpenListener;
import com.gyf.barlibrary.ImmersionBar;
import com.lib.funsdk.support.FunSupport;
import com.lib.funsdk.support.OnFunDeviceListener;
import com.lib.funsdk.support.OnFunDeviceOptListener;
import com.lib.funsdk.support.models.FunDevStatus;
import com.lib.funsdk.support.models.FunDevType;
import com.lib.funsdk.support.models.FunDevice;
import com.lib.funsdk.support.models.FunLoginType;
import com.lib.sdk.struct.H264_DVR_FILE_DATA;
import com.nostra13.universalimageloader.utils.L;
import com.umeng.analytics.MobclickAgent;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends SlidingFragmentActivity
        implements OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {
    public static final int MY_DEVICE = 0;
    public static final int BBS = 1;
    public static final int SHOP = 2;
    public static final int USERCENTER = 3;
    private TextView tv_statusBar_mian;
    private TextView tv_statusBar_slide;
    public TextView tv_statusBar_shop;
    public ViewPager viewPager;
    private ExpandableListView mLayoutLv;
    private List<ExpandableLayout> mLayouts = new ArrayList<ExpandableLayout>();
    private LayoutAdapter mLayoutAdapter;
    public RadioButton mMyDeviceRBT;
    private RadioButton mBbsRBT;
    public RadioButton mDiscoveryRBT;
    private RadioButton mUserCenterRBT;
    public int currentPage;
    public View mBlock;
    public LinearLayout topBar;
    private LinearLayout mMoreLayout;
    private LinearLayout mAddLayout;
    private SlidingMenu slidingMenu;
    private List<Device> spaces = new ArrayList<Device>();
    private List<Device> mWlans = new ArrayList<Device>();
    private List<Device> mSwitchs = new ArrayList<Device>();
    private List<Device> mSockets = new ArrayList<Device>();
    private List<Device> mRemotes = new ArrayList<Device>();
    private List<Device> mLights = new ArrayList<Device>();
    private List<Device> mLocks = new ArrayList<Device>();
    private List<Device> mCameras = new ArrayList<Device>();
    private List<FunDevice> mFunCameras = new ArrayList<FunDevice>();
    private List<Device> mCurtain = new ArrayList<Device>();
    private List<Device> wireless = new ArrayList<Device>();

    private GridView mDeviceGridView;
    private WlanHorizonAdapter wlanAdapter;
    public static MainActivity mainActivity;
    public static final int STARTACTIVITY_SHARE_TARGET_ACTIVITY = 0;
    public static final int STARTACTIVITY_SHARE_CONTENT_ACTIVITY = 1;
    public static final int STARTACTIVITY_ENV_AUTHOR_ACTIVITY = 2;
    public static final int STARTACTIVITY_DEVICE_AUTHOR_ACTIVITY = 3;
    public static final int SINGLE_DEVICE_CTRL = 4;
    public static final int SINGLE_DEVICE_CTRL1 = 41;
    public static final int GET_ORDER_SUCCESS = 5;
    public static final int GET_UPDATE_PROGRESS = 6;
    public static final int EDIT_DEVICE_NAME_SUCCESS = 15;
    public static final int EDIT_DEVICE_NAME_FAIL = 16;
    private float density;
    private int size;
    private int gridviewWidth;
    private boolean running = true;
    private boolean running1;
    private String[] option;
    private NormalListDialog mNormalListDialog;
    private BaseAnimatorSet bas_in;
    private BaseAnimatorSet bas_out;
    private EditDeviceNameDialog mEditNameDialog;
    private NormalDialog mNormalDialog;
    private NormalDialog mNormalDialog1;
    private NormalDialog mNormalDialog2;
    private NormalDialog mNormalDialog3;
    private boolean power;
    private int position;
    private Device d;
    private int DEVICE_DENSITY_DPI;
    private long exitTime = 0;// 点击两次退出程序所需的常量exitTime
    private DisplayMetrics dm;
    private OnDataUpdateListener onDataUpdateListener;
    private Dialog dialog;
    private TextView mPercentT;
    private ImageView mPerventImg;
    private TextView mDeviceNameT;
    private TextView mHome;
    private boolean needToShow = true;
    private ProgressDialog pd;
    private String appDownloadUrl;
    private boolean downloading = false;
    private boolean needUpdateApp = true;
    private boolean needUpdateDevice = true;
    private boolean needNoticeSetup = true;
    private int type;
    private int num;
    private List<String> mids = new ArrayList<String>();
    private String checkCmd = "";
    private SVProgressHUD mSVProgressBar;
    private String harddeviceversion = "";
    private boolean slidingMenuShowing = false;
    private MyDBHelper myDBHelper;
    private boolean flag=false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置无标题
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);
        setBehindContentView(R.layout.activity_main_behind);
        mainActivity = this;
        dm = new DisplayMetrics();
        initView();
        initEvent();
        boolVersion();
        setSlidiingMenu();
        initMqtt();
        initData();
        initListener();
        myDBHelper = new MyDBHelper(getApplicationContext());
        KeyManager.getInstance().initKeyName();
    }

    private void initSocket() {
        SocketManager.getInstance().initSocket(MainActivity.this);
    }

    private void initMqtt() {
        SocketManager.getInstance().user_id = (String) SPUtils.get(getApplicationContext(), "user_id", "");
        if (SocketManager.getInstance().user_id != null && !SocketManager.getInstance().user_id.equals("")) {
            SocketManager.getInstance().initRemoteConnect(MainActivity.this);
            SocketManager.getInstance().setAppVersionListener(new AppVersionListener() {

                @Override
                public void newVersion(String versionName, int versionCode, String downloadUrl, String size) {
                    // TODO Auto-generated method stub
                    if (needUpdateApp) {
                        needUpdateApp = false;
                        Log.i("wmy", 155 + getPackageName() + "升级");
                        Message m = Message.obtain();
                        m.what = 8;
                        Version v = new Version(versionName, versionCode, downloadUrl, size);
                        m.obj = v;
                        mHandler.sendMessage(m);
                    }
                }
            });
            SocketManager.getInstance().setDeviceVersionListener(new DeviceVersionListener() {

                @Override
                public void newVersion(DeviceVersion dv) {
                    // TODO Auto-generated method stub
                    if (needUpdateDevice) {
                        needUpdateDevice = false;
                        Log.i("wmy", "212" + getPackageName() + "固件升级");
                        Message message = Message.obtain();
                        message.what = 11;
                        message.obj = dv;
                        mHandler.sendMessage(message);
                    }
                }
            });
            SocketManager.getInstance().setOnExtrusionListener(new OnExtrusionListener() {

                @Override
                public void OnExtrusion() {
                    // TODO Auto-generated method stub
                    // Log.i("wmy", )
                    mHandler.sendEmptyMessage(12);
                }
            });
        }
    }

    private void initGridView1() {
        // 如果APP在前台 则处理 否则 return
        // 获取网关集合
        // 判断网关数量，当网关数量有改变时，才更新 否则只notify
        if (!Util.isRunningForeground(mainActivity)) {
            return;
        }
        mWlans = DeviceManager.getInstance().getWlans();
        size = mWlans.size();
        if (onDataUpdateListener != null) {
            onDataUpdateListener.update(mWlans.size(), mWlans.size());
        }
        gridviewWidth = (int) (size * (100 + 4) * density);
        // DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        density = dm.density;
        int itemWidth = (int) (100 * density * 0.8);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(gridviewWidth,
                LinearLayout.LayoutParams.FILL_PARENT);
        mDeviceGridView.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
        mDeviceGridView.setNumColumns(size); // 设置列数量=列表集合数
        mDeviceGridView.setColumnWidth(itemWidth); // 设置列表项宽
        mDeviceGridView.setHorizontalSpacing(0); // 设置列表项水平间距
        mDeviceGridView.setStretchMode(GridView.NO_STRETCH);
        wlanAdapter = new WlanHorizonAdapter(mainActivity, mWlans);
        mDeviceGridView.setAdapter(wlanAdapter);
    }

    private void getOrder() {
        if (NetUtil.isNetworkAvailable(getApplicationContext())) {
            if (!Util.isLogin(getApplicationContext())) {
                return;
            }
            RequestParams params = new RequestParams(HttpURL.GET_ORDER_URL);
            params.setAsJsonContent(true);
            JSONObject obj = new JSONObject();
            try {
                obj.put("key", "10000");
                obj.put("requestTime", "" + System.currentTimeMillis());
                obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                Log.d("test", " get all order = " + obj.toString());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            params.setBodyContent(obj.toString());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    // Log.e("wmy", "get all order =" + result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String resultCode = jsonObject.getString("resultCode");

                        if (resultCode.equals("1")) {
                            DeviceManager.getInstance().clearOrder();
                            DeviceManager.getInstance().getCurrentOrder().setStatus(0);
                            JSONArray ja = jsonObject.getJSONArray("data");
                            for (int i = 0; i < ja.length(); i++) {
                                JSONObject jo = ja.getJSONObject(i);
                                String id = jo.getString("id");
                                String publishUserId = jo.getString("publishUserId");
                                String publishUserName = jo.getString("publishUserName");
                                String publishUserPhone = jo.getString("publishUserPhone");
                                int createTime = jo.getInt("createTime");
                                long installerTime = jo.getLong("installerTime");
                                String explain = jo.optString("explain");
                                int status = jo.getInt("status");
                                String shopOrderNumber = jo.optString("shopOrderNumber");
                                double score = jo.getDouble("score");
                                String region = jo.getString("region");
                                String address = jo.getString("address");
                                Order order = new Order(id, publishUserId, publishUserName, publishUserPhone,
                                        createTime, installerTime, explain, status, score, region, address,
                                        shopOrderNumber);
                                // boolean need = false;
                                // if((System.currentTimeMillis()-installerTime)>24*60*60*1000){
                                // need = true;
                                // }
                                if ((status == 8 || status == 2) && score == 0) {
                                    DeviceManager.getInstance().setCurrentOrder(order);
                                }
                                DeviceManager.getInstance().addOrder(order);
                            }
                            Message msg = Message.obtain();
                            msg.what = GET_ORDER_SUCCESS;
                            mHandler.sendMessage(msg);
                        } else if (resultCode.equals("10003")) {
                            // 在这里判断token有效性
                            Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onCancelled(CancelledException arg0) {
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                    // lt.error();
                }

                @Override
                public void onFinished() {
                }
            });
        }
    }

    public void boolVersion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            getWindow().addFlags(
             WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            // 改变titlebar的高度
            int statusbarHeight = BarUtils.getStatusBarHeight(this);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tv_statusBar_slide.getLayoutParams();
            layoutParams.height = statusbarHeight;
            tv_statusBar_slide.setLayoutParams(layoutParams);
            RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
                    .getLayoutParams();
            layoutParams1.height = statusbarHeight;
            tv_statusBar_mian.setLayoutParams(layoutParams1);
            LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) tv_statusBar_shop.getLayoutParams();
            layoutParams2.height = statusbarHeight;
            tv_statusBar_shop.setLayoutParams(layoutParams2);
            tv_statusBar_mian.setVisibility(View.VISIBLE);
            tv_statusBar_shop.setVisibility(View.GONE);
        } else {
            tv_statusBar_mian.setVisibility(View.GONE);
            tv_statusBar_slide.setVisibility(View.GONE);
            tv_statusBar_shop.setVisibility(View.GONE);
        }
    }

    public void boolVersion1() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            // getWindow().addFlags(
            // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            // 改变titlebar的高度
            int statusbarHeight = BarUtils.getStatusBarHeight(this);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tv_statusBar_slide.getLayoutParams();
            layoutParams.height = statusbarHeight;
            tv_statusBar_slide.setLayoutParams(layoutParams);
            RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
                    .getLayoutParams();
            layoutParams1.height = statusbarHeight;
            tv_statusBar_mian.setLayoutParams(layoutParams1);
            tv_statusBar_mian.setVisibility(View.VISIBLE);

        } else {
            tv_statusBar_mian.setVisibility(View.GONE);
            tv_statusBar_slide.setVisibility(View.GONE);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case 0:
                    initGridView1();
                    // 检查网关连接状态
                    if (mLayouts.size() > 0) {
                        mLayouts.get(0).setDevices(DeviceManager.getInstance().getWlans());
                        mLayouts.get(1).setDevices(DeviceManager.getInstance().getWlans());
                        mLayouts.get(2).setDevices(DeviceManager.getInstance().getRemotes());
                        mLayouts.get(3).setDevices(DeviceManager.getInstance().getCameras());
                        mLayouts.get(4).setDevices(DeviceManager.getInstance().getWireless());
                        mLayouts.get(5).setDevices(DeviceManager.getInstance().getSwitchs());
                        mLayouts.get(6).setDevices(DeviceManager.getInstance().getCurtains());
                        mLights = DeviceManager.getInstance().getLights();
                        mLayouts.get(7).setDevices(DeviceManager.getInstance().getSockets());
                        mLayouts.get(8).setDevices(DeviceManager.getInstance().getLights());
                        mLayouts.get(9).setDevices(DeviceManager.getInstance().getLocks());
                        if (mLayoutAdapter == null) {
                            mLayoutAdapter = new LayoutAdapter();
                            mLayoutLv.setAdapter(mLayoutAdapter);
                        } else {
                            mLayoutAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case 1:
                    Log.e("wmy", "刷新lv mLayouts.size() = " + mLayouts.size());
                    if (mLayouts.size() > 0) {
                        mLayouts.get(0).setDevices(DeviceManager.getInstance().getWlans());
                        mLayouts.get(1).setDevices(DeviceManager.getInstance().getWlans());
                        mLayouts.get(2).setDevices(DeviceManager.getInstance().getRemotes());
                        mLayouts.get(3).setDevices(DeviceManager.getInstance().getCameras());
                        mLayouts.get(4).setDevices(DeviceManager.getInstance().getWireless());
                        mLayouts.get(5).setDevices(DeviceManager.getInstance().getSwitchs());
                        mLayouts.get(6).setDevices(DeviceManager.getInstance().getCurtains());
                        mLights = DeviceManager.getInstance().getLights();
                        mLayouts.get(7).setDevices(DeviceManager.getInstance().getSockets());
                        mLayouts.get(8).setDevices(DeviceManager.getInstance().getLights());
                        mLayouts.get(9).setDevices(DeviceManager.getInstance().getLocks());
                        if (mLayoutAdapter == null) {
                            mLayoutAdapter = new LayoutAdapter();
                            mLayoutLv.setAdapter(mLayoutAdapter);
                        } else {
                            mLayoutAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case EDIT_DEVICE_NAME_SUCCESS:
                    getAllDevice();

                    mEditNameDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "编辑成功！", Toast.LENGTH_SHORT).show();
                    break;
                case EDIT_DEVICE_NAME_FAIL:
                    mEditNameDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "编辑失败！", Toast.LENGTH_SHORT).show();
                    break;
                case SINGLE_DEVICE_CTRL:
                    power = (Boolean) msg.obj;
                    position = msg.arg1;
                    onOrOff(position, power, msg.arg2);
                    break;
                case SINGLE_DEVICE_CTRL1:
                    power = (Boolean) msg.obj;
                    position = msg.arg1;
                    onOrOff1(position, power);
                    break;
                case GET_ORDER_SUCCESS:
                    // 获取了所有的订单后
                    // 遍历其的状态
                    // 如果已安装 尚未评分 且安装时间与现在已超过1天
                    // 弹出评分界面 引导用户评分
                    List<Order> orders = DeviceManager.getInstance().getOrders();
                    if (!needToShow) {
                        return;
                    }
                    for (int i = 0; i < orders.size(); i++) {
                        if (orders.get(i).getStatus() == 2) {
                            if (DeviceManager.getInstance().getCurrentOrder() == null) {
                                DeviceManager.getInstance().setCurrentOrder(orders.get(i));
                            }
                        }
                        if (orders.get(i).isNeedToScore()) {
                            final int p = i;
                            mNormalDialog = new NormalDialog(MainActivity.this);
                            mNormalDialog.content("您有已完成的订单:订单" + orders.get(i).getId() + " 尚未评分，是否立即为安装工程师打分？")
                                    .style(NormalDialog.STYLE_TWO)//
                                    .titleTextSize(18)//
                                    .showAnim(bas_in)//
                                    .dismissAnim(bas_out)//
                                    .show();
                            mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    mNormalDialog.dismiss();
                                    needToShow = false;
                                }
                            }, new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    mNormalDialog.dismiss();
                                    Intent intent = new Intent(MainActivity.this, ScoreActivity.class);
                                    intent.putExtra("position", p);
                                    startActivity(intent);
                                }
                            });
                            break;
                        }
                    }
                    break;
                case GET_UPDATE_PROGRESS:
                    try {
                        JSONObject jo = new JSONObject(msg.obj.toString());
                        String g = jo.getString("g");
                        JSONObject jo1 = new JSONObject(g);
                        int status = jo1.getInt("status");
                        switch (status) {
                            case 0:
                                // Log.i("wmy", "升级正常 " + msg.obj);
                                int progress = jo1.getInt("progress");
                                if (progress == 20) {
                                    mPerventImg.setImageResource(R.drawable.p20);
                                    mPercentT.setText("升级进度：" + progress + "%");
                                } else if (progress == 40) {
                                    mPerventImg.setImageResource(R.drawable.p40);
                                    mPercentT.setText("升级进度：" + progress + "%");
                                } else if (progress == 60) {
                                    mPerventImg.setImageResource(R.drawable.p60);
                                    mPercentT.setText("升级进度：" + progress + "%");
                                } else if (progress == 80) {
                                    mPerventImg.setImageResource(R.drawable.p80);
                                    mPercentT.setText("升级进度：" + progress + "%");
                                } else if (progress == 100) {
                                    mPerventImg.setImageResource(R.drawable.p100);
                                    mPercentT.setText("升级完成");
                                    dialog.dismiss();
                                    ToastShow.Show(getApplicationContext(), "升级完成！");
                                }
                                break;
                            case 1:
                                ToastShow.Show(getApplicationContext(), "域名解析失败");
                                break;
                            case 2:
                                ToastShow.Show(getApplicationContext(), "服务器连接失败");
                                break;
                            case 3:
                                ToastShow.Show(getApplicationContext(), "文件请求失败");
                                break;
                            case 4:
                                ToastShow.Show(getApplicationContext(), "文件请求响应失败");
                                break;
                            case 5:
                                ToastShow.Show(getApplicationContext(), "服务器无响应");
                                break;
                            case 6:
                                ToastShow.Show(getApplicationContext(), "文件升级中断了");
                                break;
                            case 7:
                                ToastShow.Show(getApplicationContext(), "内存升级失败");
                                break;

                            default:
                                break;
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case 7:
                    // Log.i("wmy", "MainActivity530" + msg.obj.toString());
                    if (!Util.isRunningForeground(MainActivity.this)) {
                        ToastShow.Show(MainActivity.this, msg.obj.toString());
                        return;
                    }
                    mNormalDialog = new NormalDialog(MainActivity.this);
                    mNormalDialog.content(msg.obj.toString()).style(NormalDialog.STYLE_TWO)//
                            .titleTextSize(18)//
                            .showAnim(bas_in)//
                            .dismissAnim(bas_out)//
                            .show();
                    mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            Intent intent = new Intent(MainActivity.this, OrderActivity.class);
                            mNormalDialog.dismiss();
                        }
                    }, new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mNormalDialog.dismiss();
                            Intent intent = new Intent(MainActivity.this, OrderActivity.class);
                            startActivity(intent);
                        }
                    });
                    break;
                case 8:
                    if (!needUpdateApp) {
                        return;
                    }
                    if (!Util.isRunningForeground(MainActivity.this)) {
                        ToastShow.Show(MainActivity.this, msg.obj.toString());
                        return;
                    }
                    Version v = (Version) msg.obj;
                    final String downloadUrl = v.getDownloadUrl();
                    appDownloadUrl = downloadUrl;
                    String version = v.getVersion();
                    int versionCode = v.getVersionCode();
                    String size = v.getSize();
                    mNormalDialog = new NormalDialog(MainActivity.this);
                    mNormalDialog.content(version + "\n最新版本大小：" + size + "M\n是否立即更新？").style(NormalDialog.STYLE_TWO)//
                            .titleTextSize(18)//
                            .showAnim(bas_in)//
                            .dismissAnim(bas_out)//
                            .show();
                    mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mNormalDialog.dismiss();
                            needUpdateApp = false;
                        }
                    }, new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mNormalDialog.dismiss();
                            // Intent intent = new Intent(MainActivity.this,
                            // OrderActivity.class);
                            // startActivity(intent);
                            if (Build.VERSION.SDK_INT >= 23) {
                                if (ContextCompat.checkSelfPermission(getApplicationContext(),
                                        Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                    boolean should = checkShould();
                                    if (should) {
                                        askPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
                                    } else {
                                        ActivityCompat.requestPermissions(MainActivity.this,
                                                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                                        Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                0);
                                    }
                                } else {
                                    downloadNewVersion(downloadUrl);
                                }
                            } else {
                                downloadNewVersion(downloadUrl);
                            }
                            // downloadNewVersion(downloadUrl);
                        }
                    });
                    break;
                case 9:
                    downloading = false;
                    pd.dismiss();
                    ToastShow.Show(MainActivity.this, "下载完成");
                    // 下载完成后安装
                    String savedFilePath = (String) msg.obj;
                    Log.i("wmy", "下载完毕" + savedFilePath);
                    Intent intent = new Intent();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.setAction(Intent.ACTION_VIEW);
                        Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),
                                "com.dotstone.chipism.fileprovider", new File(savedFilePath));
                        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(new File(savedFilePath)),
                                "application/vnd.android.package-archive");
                    }
                    startActivity(intent);
                    break;
                case 10:
                    pd.setProgress(msg.arg1);
                    break;
                case 11:
                    if (downloading) {
                        return;
                    }
                    if (!needUpdateDevice) {
                        return;
                    }
                    if (!Util.isRunningForeground(MainActivity.this)) {
                        ToastShow.Show(MainActivity.this, msg.obj.toString());
                        return;
                    }
                    final DeviceVersion dv = (DeviceVersion) msg.obj;
                    // final String newVersion = (String) msg.obj;
                    // final int newcode = msg.arg1;
                    // final int oldcode = msg.arg2;
                    mNormalDialog1 = new NormalDialog(MainActivity.this);
                    mNormalDialog1
                            .content("您的网关设备有新的固件版本：" + dv.getNewVersion() + "可供升级\n是否立即更新？点击取消后您也可通过长按网关设备查看并升级固件版本。")
                            .style(NormalDialog.STYLE_TWO)//
                            .titleTextSize(18)//
                            .showAnim(bas_in)//
                            .dismissAnim(bas_out)//
                            .show();
                    mNormalDialog1.setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mNormalDialog1.dismiss();
                            needUpdateDevice = false;
                        }
                    }, new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mNormalDialog1.dismiss();
                            updateWlan(dv.getNewVersion(), dv.getNewVersionCode(), dv.getSocketVersionCode(),
                                    dv.getDownloadUrl());
                            ToastShow.Show(getApplicationContext(), "正在进行固件升级，升级大概需要30-60秒。");
                        }
                    });
                    break;
                case 12:
                    mNormalDialog3 = new NormalDialog(MainActivity.this);
                    mNormalDialog3.setLeftBtnContent("退出");

                    mNormalDialog3.content("您的帐号在另一台设备登录。如非本人操作，则密码可能已泄露，建议修改密码。").style(NormalDialog.STYLE_TWO)//
                            .titleTextSize(18)//
                            .showAnim(bas_in)//
                            .dismissAnim(bas_out)//
                            .show();
                    mNormalDialog3.setOnDismissListener(new OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            // TODO Auto-generated method stub
                            DeviceManager.getInstance().clearDevice();
                            DeviceManager.getInstance().clearHouse();
                            DeviceManager.getInstance().clearRoom();
                            SocketManager.getInstance().stopMqtt();
                            SocketManager.getInstance().sMap.clear();
                            SPUtils.clear(getApplicationContext());
                            finish();
                            System.exit(0);
                        }
                    });
                    mNormalDialog3.setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mNormalDialog3.dismiss();
                            DeviceManager.getInstance().clearDevice();
                            DeviceManager.getInstance().clearHouse();
                            DeviceManager.getInstance().clearRoom();
                            SocketManager.getInstance().stopMqtt();
                            SocketManager.getInstance().sMap.clear();
                            SPUtils.clear(getApplicationContext());
                            finish();
                            System.exit(0);
                        }
                    }, new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mNormalDialog3.dismiss();
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            DeviceManager.getInstance().clearDevice();
                            DeviceManager.getInstance().clearHouse();
                            DeviceManager.getInstance().clearRoom();
                            SocketManager.getInstance().stopMqtt();
                            SocketManager.getInstance().sMap.clear();
                            SPUtils.clear(getApplicationContext());
                            startActivity(intent);
                            finish();
                        }
                    });
                    break;
                case 13:
                    Log.i("wmy", "全部获取完毕");
                    if (mSVProgressBar.isShowing()) {
                        //mSVProgressBar.dismiss();
                        //ToastShow.Show(getApplicationContext(), "状态更新成功");
                    }
                    mLayoutAdapter.notifyDataSetChanged();
                    SocketManager.getInstance().setNeedToCheck(false);
                    break;
                default:
                    break;
            }
        }
    };

    @SuppressLint("NewApi")
    private boolean checkShould() {
        if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            Log.e("wmy", "曾被设置永不提示");
            return true;
        } else {
            Log.e("wmy", "未曾设置永不提示");
            return false;
        }
    }

    private void askPermission(String permission) {
        String request = "";
        // if (permission.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
        request = "储存权限被禁止，是否前往设置界面开启？";
        // }
        mNormalDialog = new NormalDialog(MainActivity.this);
        mNormalDialog.content(request).style(NormalDialog.STYLE_TWO)//
                .titleTextSize(18)//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                mNormalDialog.dismiss();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                mNormalDialog.dismiss();
                Intent localIntent = new Intent();
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", MainActivity.this.getPackageName(), null));
                startActivity(localIntent);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Log.e("wmy", "调用权限" + requestCode + " " + permissions[0] + " " +
        // permissions[1] + " " + grantResults[0] + " "
        // + grantResults[1]);
        if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            if (appDownloadUrl != null && grantResults[0] == 0) {
                downloadNewVersion(appDownloadUrl);
            } else {
                ToastShow.Show(getApplicationContext(), "权限已被禁止");
            }
        }
    }

    private void askPermission(String permission[]) {

        String request = "";
        if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            request = "使用储存权限被禁止，是否取消禁用？";
        }
        mNormalDialog2 = new NormalDialog(MainActivity.this);
        mNormalDialog2.content(request).style(NormalDialog.STYLE_TWO)//
                .titleTextSize(18)//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        mNormalDialog2.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                mNormalDialog2.dismiss();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                mNormalDialog2.dismiss();
                Intent localIntent = new Intent();
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                startActivity(localIntent);
            }
        });
    }

    private void updateWlan(final String version, final int newcode, int oldcode, final String downloadUrl) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                List<Device> wlans = DeviceManager.getInstance().getWlans();
                for (int i = 0; i < wlans.size(); i++) {
                    if (SocketManager.getInstance().sMap.get(wlans.get(i).getDeviceID()) != null) {
                        String socketVersion = SocketManager.getInstance().sMap.get(wlans.get(i).getDeviceID())
                                .getVersion();
                        int vcode = Util.getVersionCode(socketVersion);
                        Log.e("wmy", "wlans.get(i).getDeviceID() = " + wlans.get(i).getDeviceID() + " vcode = " + vcode
                                + " newcode = " + newcode);
                        if (vcode < newcode) {
                            Log.e("wmy", "有需要升级的网关" + wlans.get(i).getDeviceID());
                            // SocketManager.getInstance().sMap.get(wlans.get(i).getDeviceID()).update();
                            SocketManager.getInstance().sMap.get(wlans.get(i).getDeviceID()).normalUpdate(version,
                                    downloadUrl);
                        }
                    }
                }
            }
        }).start();
    }

    protected boolean cancelDownload;
    private AlertDialog dialog_download;
    protected int lastProgress;

    protected void downloadNewVersion(final String urlString) {
        downloading = true;
        pd = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        pd.setMessage(getString(R.string.downloading));
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(false);// android 高版本对话框点击消失
        pd.show();
        pd.setProgress(0);
        pd.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface arg0) {
                cancelDownload = true;
            }
        });

        new Thread() {

            public void run() {
                try {
                    InputStream input = null;
                    HttpURLConnection urlConn = null;
                    URL url = new URL(urlString);
                    urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setRequestProperty("Accept-Encoding", "identity");
                    urlConn.setReadTimeout(10000);
                    urlConn.setConnectTimeout(10000);
                    input = urlConn.getInputStream();
                    int total = urlConn.getContentLength();
                    File file = null;
                    OutputStream output = null;
                    if (!new File(android.os.Environment.getExternalStorageDirectory().getPath() + "/cache").exists()) {
                        new File(android.os.Environment.getExternalStorageDirectory().getPath() + "/cache").mkdirs();
                    }
                    // String savedFilePath =
                    // android.os.Environment.getRootDirectory().getPath()
                    // + "/cache/xintek.apk";
                    String savedFilePath = android.os.Environment.getExternalStorageDirectory().getPath()
                            + "/cache/xintek.apk";
                    file = new File(savedFilePath);
                    output = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int temp = 0;
                    int read = 0;
                    while ((temp = input.read(buffer)) != -1) {
                        if (cancelDownload) {
                            throw new CancelException();
                        }
                        output.write(buffer, 0, temp);
                        read += temp;
                        float progress = ((float) read) / total;
                        int progress_int = (int) (progress * 100);
                        if (lastProgress != progress_int) {
                            lastProgress = progress_int;
                            Message msg = new Message();
                            msg.what = 10;// downloading
                            msg.arg1 = progress_int;
                            mHandler.sendMessage(msg);
                        } else {
                            // do not send msg
                        }
                    }
                    output.flush();
                    output.close();
                    input.close();
                    Message msg = new Message();
                    msg.what = 9;
                    msg.obj = savedFilePath;
                    mHandler.sendMessage(msg);
                } catch (CancelException e) {
                    Log.e("wmy", "取消下载啦");
                    cancelDownload = false;
                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(5);
                }
            }

            ;
        }.start();
    }

    public void getAllDevice() {
        if (NetUtil.isNetworkAvailable(getApplicationContext())) {
            if (!Util.isLogin(getApplicationContext())) {
                return;
            }
            RequestParams params = new RequestParams(HttpURL.GET_DEVICE_URL);
            params.setAsJsonContent(true);
            JSONObject obj = new JSONObject();
            try {
                obj.put("key", "10000");
                obj.put("hid", DeviceManager.getInstance().hid);
                obj.put("requestTime", "" + System.currentTimeMillis());
                obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                // Log.d("test", " get all obj = " + obj.toString());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            params.setBodyContent(obj.toString());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    // DeviceManager.getInstance().clearDevice();
                    if (mSVProgressBar.isShowing()) {
                        mSVProgressBar.dismiss();
                    }
                    Log.e("wmy", "get all device =" + result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String resultCode = jsonObject.getString("resultCode");
                        if (resultCode.equals("1")) {
                            DeviceManager.getInstance().clearDevice();
                            JSONArray data = jsonObject.getJSONArray("data");
                            // Log.e("wmy", "length " + data.length());
                            if (data.length() != 0) {
                                for (int i = 0; i < data.length(); i++) {
                                    JSONObject deviceInfo = data.getJSONObject(i).getJSONObject("deviceInfo");
                                    String deviceId = deviceInfo.getString("deviceId");
                                    String deviceWifiSSID = deviceInfo.getString("deviceWifiSSID");
                                    String deviceAddress = deviceInfo.optString("deviceAddress");
                                    int deviceType = deviceInfo.getInt("deviceType");
                                    String deviceModel = deviceInfo.getString("deviceModel");
                                    String deviceName = data.getJSONObject(i).getString("remarks");// deviceName
                                    int status = deviceInfo.optInt("deviceStatus");
                                    int role = data.getJSONObject(i).optInt("role");
                                    String userId = deviceInfo.getString("userId");
                                    String mainDeviceId = deviceInfo.optString("mainDeviceId");
                                    Device device = new Device();
                                    device.setDeviceID(deviceId);
                                    device.setDeviceWifiSsid(deviceWifiSSID);
                                    device.setDeviceType(deviceType);

                                    device.setDeviceBrand(deviceModel);
                                    device.setDeviceName(deviceName);
                                    device.setStatus(status);
                                    device.setRole(role);
                                    Log.i("wmy",
                                            getClass().getSimpleName() + "589 device.setUserId(userId) = " + userId);
                                    device.setUserId(userId);
                                    if (deviceType == DeviceType.DEVICE_TYPE_AIR_CONTROLLER
                                            || deviceType == DeviceType.DEVICE_TYPE_BOX2
                                            || deviceType == DeviceType.DEVICE_TYPE_DVD
                                            || deviceType == DeviceType.DEVICE_TYPE_FAN
                                           || deviceType == DeviceType.DEVICE_TYPE_TV
                                            || deviceType == DeviceType.DEVICE_TYPE_PROJECTOR) {
                                        // 是遥控器
                                        JSONArray ja = data.getJSONObject(i).getJSONArray("deviceButton");
                                        List<Key> keys = new ArrayList<Key>();
                                        for (int n = 0; n < ja.length(); n++) {
                                            Key key = new Key();
                                            JSONObject joKey = ja.getJSONObject(n);
                                            key.setKeyNum(joKey.getInt("position"));
                                            key.setCodeValue(joKey.getString("buttonCmd"));
                                            keys.add(key);
                                        }
                                        device.setKeys(keys);
                                    }

                                    if (deviceType != DeviceType.DEVICE_TYPE_WLAN) {
                                        Log.i("wmy", deviceName + "设置主ID ");
                                        device.setMainDeviceId(mainDeviceId);
                                    }
                                    Log.i("wmy", 1088 + " " + deviceName + " 获取设备状态 " + status);
                                    device.setDeviceAddress(deviceAddress);
                                    Log.i("wmy", 1090 + " " + deviceName + " 获取设备状态 " + status);
                                    DeviceManager.getInstance().addDevice(device);
                                    myDBHelper.addStatus(deviceId, false, 0, 0, 0);
                                }
                            }

                            List<String> nullMids = Util.checkNull();
                            if (nullMids.size() == 0) {
                                Log.e("wmy", "1101获取全部设备 没有需要重新获取的mid");
                                Message msg = Message.obtain();
                                msg.what = 1;
                                mHandler.sendMessage(msg);
                            } else {
                                Log.e("wmy", "1105获取全部设备 有需要重新获取的mid");
                                getNullWlan(nullMids);
                            }

                        } else if (resultCode.equals("10003")) {
                            // 在这里判断token有效性
                            Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onCancelled(CancelledException arg0) {
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                    // lt.error();
                }

                @Override
                public void onFinished() {
                }
            });
        }
    }

    public void getNullWlan(List<String> mids) {
        for (int i = 0; i < mids.size(); i++) {
            getWlanInfo(mids.get(i));
        }
    }

    private void getWlanInfo(String mid) {
        if (NetUtil.isNetworkAvailable(getApplicationContext())) {
            if (!Util.isLogin(getApplicationContext())) {
                return;
            }
            RequestParams params = new RequestParams(HttpURL.GET_WLAN_URL);
            params.setAsJsonContent(true);
            JSONObject obj = new JSONObject();
            try {
                obj.put("key", "10000");
                obj.put("deviceId", mid);
                obj.put("requestTime", "" + System.currentTimeMillis());
                obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                Log.e("wmy", " get single wlan = " + obj.toString());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            params.setBodyContent(obj.toString());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.e("wmy", "get single wlan =" + result);
                    // Dev
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String resultCode = jsonObject.getString("resultCode");
                        if (resultCode.equals("1")) {
                            JSONObject deviceInfo = jsonObject.getJSONObject("data");
                            Log.e("wmy", "deviceInfo = " + deviceInfo.toString());
                            String deviceId = deviceInfo.getString("deviceId");
                            String deviceWifiSSID = deviceInfo.getString("deviceWifiSSID");
                            String deviceAddress = deviceInfo.optString("deviceAddress");
                            int deviceType = deviceInfo.getInt("deviceType");
                            String deviceModel = deviceInfo.getString("deviceModel");
                            String deviceName = deviceInfo.getString("deviceName");// deviceName
                            int status = deviceInfo.optInt("deviceStatus");
                            int role = deviceInfo.optInt("role");
                            String userId = deviceInfo.getString("userId");
                            String mainDeviceId = deviceInfo.optString("mainDeviceId");
                            Device device = new Device();
                            device.setDeviceID(deviceId);
                            device.setDeviceWifiSsid(deviceWifiSSID);
                            device.setDeviceType(deviceType);
                            device.setDeviceBrand(deviceModel);
                            device.setDeviceName(deviceName);
                            device.setStatus(status);
                            device.setRole(role);
                            device.setUserId(userId);
                            if (deviceType != DeviceType.DEVICE_TYPE_WLAN) {
                                device.setMainDeviceId(mainDeviceId);
                            } else {
                                device.setMainDeviceId(deviceId);
                            }
                            device.setDeviceAddress(deviceAddress);
                            DeviceManager.getInstance().addDevice(device);
                            device = null;

                            Log.e("wmy", "1118获取全部设备 没有需要重新获取的mid");
                            Message msg = Message.obtain();
                            msg.what = 1;
                            mHandler.sendMessage(msg);

                        } else if (resultCode.equals("10003")) {
                            // 在这里判断token有效性
                            Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                            finish();
                        }else if (resultCode.equals("10001")) {
                            Message msg = Message.obtain();
                            msg.what = 1;
                            mHandler.sendMessage(msg);

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onCancelled(CancelledException arg0) {
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                    // lt.error();
                }

                @Override
                public void onFinished() {
                }
            });
        }
    }

    public void setSlidiingMenu() {
        slidingMenu = getSlidingMenu();
        slidingMenu.setMode(SlidingMenu.LEFT);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        slidingMenu.setShadowDrawable(R.drawable.shadow);
        slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        slidingMenu.setFadeDegree(0.35f);
        slidingMenu.setOnCloseListener(new OnCloseListener() {

            @Override
            public void onClose() {
                // TODO Auto-generated method stub
                Log.i("wmy", "关闭侧滑菜单");
                if (mSVProgressBar.isShowing()) {
                    mSVProgressBar.dismiss();
                }
                slidingMenuShowing = false;
                for (int i = 0; i < mLayoutAdapter.getGroupCount(); i++) {
                    mLayoutLv.collapseGroup(i);
                }
            }
        });
        slidingMenu.setOnOpenListener(new OnOpenListener() {

            @Override
            public void onOpen() {
                // TODO Auto-generated method stub
                slidingMenuShowing = true;
                Log.i("wmy", "打开侧滑菜单");
            }
        });
    }

    private void initEvent() {
        // TODO Auto-generated method stub
        mMyDeviceRBT.setOnClickListener(this);
        mBbsRBT.setOnClickListener(this);
        mDiscoveryRBT.setOnClickListener(this);
        mUserCenterRBT.setOnClickListener(this);
        mMoreLayout.setOnClickListener(this);
        mAddLayout.setOnClickListener(this);
        mLayoutLv.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
                                        long id) {
                // TODO Auto-generated method stub
                switch (groupPosition) {
                    case 0: // 网关

                        break;
                    case 1:// 空间

                        break;
                    case 2: // 遥控器
                        Log.e("mLayouts==","mLayouts= "+mLayouts.size()+"groupPosition= "+groupPosition+"childPosition= "+childPosition);
                        Log.e("mLayouts==","xxx= "+mLayouts.get(groupPosition).toString());
                        Log.e("mLayouts==","xxx= "+mLayouts.get(groupPosition).getDevices().toString());
                        Log.e("mLayouts==","xxx= "+mLayouts.get(groupPosition).getDevices().get(childPosition).toString());
                        Log.e("mLayouts==","xxx= "+mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType());
                        if (mLayouts.get(groupPosition)!=null && mLayouts.get(groupPosition).getDevices()!=null) {
                        int type = mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType();
                        String deviceModel = mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceBrand();
                        switch (type) {
                            case DeviceType.DEVICE_TYPE_DVD:
                                Intent intent2 = new Intent(getApplicationContext(), RemoteDVDActivity.class);
                                intent2.putExtra("position", childPosition);
                                startActivity(intent2);
                                break;
                            case DeviceType.DEVICE_TYPE_PROJECTOR:
                                Intent intent3 = new Intent(getApplicationContext(), RemoteProjectActivity.class);
                                intent3.putExtra("position", childPosition);
                                startActivity(intent3);
                                break;
                            case DeviceType.DEVICE_TYPE_TV:
                                Intent intent4 = new Intent(getApplicationContext(), RemoteTVActivity.class);
                                intent4.putExtra("position", childPosition);
                                startActivity(intent4);
                                break;
                            case DeviceType.DEVICE_TYPE_FAN:
                                Intent intent5 = new Intent(getApplicationContext(), RemoteFanActivity.class);
                                intent5.putExtra("position", childPosition);
                                startActivity(intent5);
                                break;
                            // case DeviceType.DEVICE_TYPE_SATELLITE:
                            // Intent intent6 = new Intent(getApplicationContext(),
                            // RemoteSatelliteActivity.class);
                            // intent6.putExtra("position", childPosition);
                            // startActivity(intent6);
                            // break;
                            case DeviceType.DEVICE_TYPE_BOX2:
                                Intent intent7 = new Intent(getApplicationContext(), RemoteBoxActivity.class);
                                intent7.putExtra("position", childPosition);
                                startActivity(intent7);
                                break;
                            case DeviceType.DEVICE_TYPE_AIR_CONTROLLER:
                                Log.i("wmy", "deviceModel = " + deviceModel);
                                if (deviceModel != null && !deviceModel.equals("")) {
                                    if (deviceModel.length() == 16) {
                                        Intent intent9 = new Intent(getApplicationContext(), RemoteAirActivity1.class);
                                        intent9.putExtra("position", childPosition);
                                        intent9.putExtra("deviceModel", deviceModel);
                                        Log.i("wmy", 1349 + getClass().getSimpleName() + " deviceModel = " + deviceModel);
                                        startActivity(intent9);
                                    } else {
                                        Intent intent11 = new Intent(getApplicationContext(), RemoteAirActivity2.class);
                                        intent11.putExtra("position", childPosition);
                                        intent11.putExtra("deviceModel", deviceModel);
                                        Log.i("wmy", 1355 + getClass().getSimpleName() + " deviceModel = " + deviceModel);
                                        startActivity(intent11);
                                    }
                                } else {
                                    String model = mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceBrand();
                                    if (model != null && !model.equals("")) {
                                        if (model.length() == 16) {
                                            Intent intent9 = new Intent(getApplicationContext(), RemoteAirActivity1.class);
                                            intent9.putExtra("position", childPosition);
                                            intent9.putExtra("deviceModel", model);
                                            Log.i("wmy", 1364 + getClass().getSimpleName() + " deviceModel = " + model);
                                            startActivity(intent9);
                                        } else {
                                            Intent intent11 = new Intent(getApplicationContext(), RemoteAirActivity2.class);
                                            intent11.putExtra("position", childPosition);
                                            intent11.putExtra("deviceModel", model);
                                            Log.i("wmy", 1370 + getClass().getSimpleName() + " deviceModel = " + model);
                                            startActivity(intent11);
                                        }
                                    }
                                }
                                break;

                            default:
                                break;
                        }
                        }
                        break;
                    case 3:
                        Log.i("xwy", "进入摄像头操作界面");
                        if (mFunCameras.size() <= 0 || mCameras.size() <= 0) {
                            break;
                        }
                        if (mFunCameras.size() > childPosition) {
                            for (int i = 0; i < mFunCameras.size(); i++) {
                                if (mFunCameras.get(i).getDevSn().equals(mCameras.get(childPosition).getDeviceAddress())) {
                                    Intent intent2 = new Intent();
                                    intent2.setClass(getApplicationContext(), DeviceCameraMainActivity.class);
                                    intent2.putExtra("FUN_DEVICE_ID", mFunCameras.get(childPosition).getId());
                                    intent2.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent2);
                                    break;
                                }
                            }
                        }
                        //请求网络
//					requestToGetDeviceList();
                        break;
                    case 4://无线开关
                        if (mLayouts.get(groupPosition).getDevices().size() > childPosition) {
                        if (mLayouts.get(groupPosition).getDevices().size() > childPosition) {
                            DeviceManager.getInstance()
                                    .setmWlanId(mLayouts.get(groupPosition).getDevices().get(childPosition).getMainDeviceId());
                            Intent intent222 = new Intent(MainActivity.this, WirelessSwitchActivity.class);
                            intent222.putExtra("address",
                                    mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                            intent222.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                            intent222.putExtra("devicetype", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType());
                            intent222.putExtra("maindeviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getMainDeviceId());
                            startActivity(intent222);
                        }
                        }
                        break;

                    case 5: // 智能开关
                        if (mLayouts.get(groupPosition).getDevices().size() > childPosition) {
                        DeviceManager.getInstance()
                                .setmWlanId(mLayouts.get(groupPosition).getDevices().get(childPosition).getMainDeviceId());
                        int type2 = mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType();
                        Intent intent=null;
                        switch (type2) {
                            case DeviceType.DEVICE_TYPE_SWITCH://电源控制盒
                                intent = new Intent(getApplicationContext(), RemoteSwitchActivity1.class);
                                intent.putExtra("address",
                                        mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                                intent.putExtra("id", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                startActivity(intent);
                                break;
                            case DeviceType.LINGHUO_SWITCH_1://一键零火开关
                                intent = new Intent(getApplicationContext(), LingHuoSwitchActivity.class);
                                intent.putExtra("address",
                                        mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                                intent.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                intent.putExtra("devicetype", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType());
                                startActivity(intent);
                                break;
                            case DeviceType.LINGHUO_SWITCH_2://2键零火开关
                                intent = new Intent(getApplicationContext(), LingHuoSwitchActivity.class);
                                intent.putExtra("address",
                                        mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                                intent.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                intent.putExtra("devicetype", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType());
                                startActivity(intent);
                                break;
                            case DeviceType.LINGHUO_SWITCH_3://3键零火开关
                                intent = new Intent(getApplicationContext(), LingHuoSwitchActivity.class);
                                intent.putExtra("address",
                                        mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                                intent.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                intent.putExtra("devicetype", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType());
                                startActivity(intent);
                                break;
                            case DeviceType.DANHUO_SWITCH_1://一键单火开关
                                intent = new Intent(getApplicationContext(), DanHuoSwitchActivity.class);
                                intent.putExtra("address",
                                        mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                                intent.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                intent.putExtra("devicetype", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType());
                                startActivity(intent);
                                break;
                            case DeviceType.DANHUO_SWITCH_2://2键单火开关
                                intent = new Intent(getApplicationContext(), DanHuoSwitchActivity.class);
                                intent.putExtra("address",
                                        mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                                intent.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                intent.putExtra("devicetype", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType());
                                startActivity(intent);
                                break;
                            case DeviceType.DANHUO_SWITCH_3://3键单火开关
                                intent = new Intent(getApplicationContext(), DanHuoSwitchActivity.class);
                                intent.putExtra("address",
                                        mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                                intent.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                intent.putExtra("devicetype", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType());
                                startActivity(intent);
                                break;
                        }
                        }
                        break;
                    case 6://窗帘
                        if (mLayouts.get(groupPosition).getDevices().size() > childPosition) {
                            DeviceManager.getInstance()
                                    .setmWlanId(mLayouts.get(groupPosition).getDevices().get(childPosition).getMainDeviceId());
                            Intent intent1111 = new Intent(MainActivity.this, RemoteCurtainActivity.class);
                            intent1111.putExtra("address",
                                    mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                            intent1111.putExtra("id", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                            intent1111.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                            startActivity(intent1111);
                        }
                        break;
                    case 7: // 智能插座
                        if (mLayouts.get(groupPosition).getDevices().size() > childPosition) {
                        DeviceManager.getInstance()
                                .setmWlanId(mLayouts.get(groupPosition).getDevices().get(childPosition).getMainDeviceId());
                        int type1 = mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceType();
                        Intent intent111=null;
                        switch (type1) {
                            case DeviceType.DEVICE_TYPE_SOCKET://转接插座
                                intent111 = new Intent(getApplicationContext(), RemoteSocketActivity1.class);
                                intent111.putExtra("address",
                                        mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                                intent111.putExtra("id", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                intent111.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                startActivity(intent111);
                                break;
                            case DeviceType.DEVICE_TYPE_CHAZUO://墙壁插座
                                intent111 = new Intent(getApplicationContext(), SocketActivity.class);
                                intent111.putExtra("address",
                                        mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                                intent111.putExtra("id", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                intent111.putExtra("deviceid", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                                startActivity(intent111);
                                break;
                           }
                        }
                        break;
                    case 8: // 灯泡
                        if (mLayouts.get(groupPosition).getDevices().size() > childPosition) {
                            DeviceManager.getInstance()
                                .setmWlanId(mLayouts.get(groupPosition).getDevices().get(childPosition).getMainDeviceId());
                        Intent intent1 = new Intent(MainActivity.this, RemoteRGBLightActivity.class);
                        intent1.putExtra("address",
                                mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceAddress());
                        intent1.putExtra("id", mLayouts.get(groupPosition).getDevices().get(childPosition).getDeviceID());
                        startActivity(intent1);
                        }
                        break;
                    case 9://门锁
                        if (mLayouts.get(groupPosition).getDevices().size() > childPosition) {
                            DeviceManager.getInstance()
                                    .setmWlanId(mLayouts.get(groupPosition).getDevices().get(childPosition).getMainDeviceId());
                            Intent intent8 = new Intent(MainActivity.this, RemoteLockActivity.class);
                            intent8.putExtra("position", childPosition);
                            startActivity(intent8);
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        mLayoutLv.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                int groupPos = (Integer) view.getTag(R.layout.item_layout);
                int childPos = (Integer) view.getTag(R.layout.item_main_device);
                if (childPos == -1) {

                } else {
                    if (groupPos != 0 && groupPos != 1) {
                        showOptionDialog(mLayouts.get(groupPos).getDevices().get(childPos),
                                mLayouts.get(groupPos).getDevices().get(childPos).getDeviceType());
                    } else if (groupPos == 0) {
                        showOptionDialog1(mLayouts.get(groupPos).getDevices().get(childPos),
                                mLayouts.get(groupPos).getDevices().get(childPos).getDeviceType());
                    } else {
                        return true;
                    }
                }
                return true;
            }
        });
        mLayoutLv.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub
                mLayoutLv.requestFocus();
                mLayoutLv.setFocusable(true);
                mLayoutLv.setFocusableInTouchMode(true);
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        mLayoutLv.setOnGroupCollapseListener(new OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                // TODO Auto-generated method stub
                if (groupPosition == 1) {
                    DeviceManager.getInstance().setNeedToCheckTemp(false);
                }
            }
        });

        mLayoutLv.setOnGroupExpandListener(new OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                // TODO Auto-generated method stub
                Log.i("wmy", "展开 groupPosition = " + groupPosition);
                if (groupPosition == 1) {
                    DeviceManager.getInstance().setNeedToCheckTemp(true);
                }
                // 监听到某个类型的设备展开 需要查询状态
                // 遍历该类型的设备
                // 找出所有的mid
                // 根据mid发送查询设备状态的指令 cmd = 87
                if (groupPosition == 2|| groupPosition == 3 ||groupPosition == 4 || groupPosition == 5 || groupPosition ==6 || groupPosition == 7 || groupPosition == 8 || groupPosition == 9) {
                    checkDeviceState(groupPosition);
                }
            }
        });
        mDeviceGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                // TODO Auto-generated method stub

            }
        });

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onResume(this);
        running1 = true;
        getOrder();
        initSocket();
        mHome.setText(DeviceManager.getInstance().homeName);
        getAllDevice();
        SocketManager.getInstance().setOnUpdateDataListener(new UpdateDataListener() {

            @Override
            public void onUpdate() {
                // TODO Auto-generated method stub
                getAllDevice();
                MainFragment.instance.getAllScene();
                MainFragment.instance.getAllRooms();
            }
        });
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPause(this);
        running1 = false;
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        running = true;
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        running = false;
    }

    private void initData() {
        // TODO Auto-generated method stub

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                // Log.i("wmy", "running = " + running);
                while (running) {

                    if (running1) {
                        Message msg = Message.obtain();
                        msg.what = 0;
                        mHandler.sendMessage(msg);
                    } else {

                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public void initView() {
        // TODO Auto-generated method stub
        mBlock = (View) findViewById(R.id.block);
        tv_statusBar_mian = (TextView) findViewById(R.id.tv_statusBar_mian);
        tv_statusBar_shop = (TextView) findViewById(R.id.tv_statusBar_shop);
        mHome = (TextView) findViewById(R.id.home);
        tv_statusBar_slide = (TextView) findViewById(R.id.tv_statusBar_slide);
        mMoreLayout = (LinearLayout) findViewById(R.id.more_layout);
        mAddLayout = (LinearLayout) findViewById(R.id.add_layout);
        mDeviceGridView = (GridView) findViewById(R.id.device_h_grid);
        mLayoutLv = (ExpandableListView) findViewById(R.id.layout_lv);
        mLayoutLv.setGroupIndicator(null);
        mSVProgressBar = new SVProgressHUD(MainActivity.this);
        initLayoutListView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            int statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    statusBarHeight);
            LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params1.setMargins(0, statusBarHeight, 0, 0);
            StatusBarHeightManager.getInstance().layoutParams1 = params1;
            mBlock.setLayoutParams(params);
        }
        topBar = (LinearLayout) findViewById(R.id.top_bar);
        viewPager = (CustomViewPager) findViewById(R.id.viewpager);

        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(metrics);
        DEVICE_DENSITY_DPI = metrics.densityDpi;
        DeviceManager.getInstance().setDEVICE_DENSITY_DPI(DEVICE_DENSITY_DPI);
        mMyDeviceRBT = (RadioButton) findViewById(R.id.device_rbtn);
        mBbsRBT = (RadioButton) findViewById(R.id.bbs_rbtn);
        mDiscoveryRBT = (RadioButton) findViewById(R.id.discovery_rbtn);
        mUserCenterRBT = (RadioButton) findViewById(R.id.usercenter_rbtn);
        Log.i("qjx", "DEVICE_DENSITY_DPI = " + DEVICE_DENSITY_DPI);
        Rect bound = new Rect(0, 0, 72 * DEVICE_DENSITY_DPI / 480, 72 * DEVICE_DENSITY_DPI / 480);
        Drawable drawable = getResources().getDrawable(R.drawable.selector_home);
        Drawable drawable1 = getResources().getDrawable(R.drawable.selector_bbs);
        Drawable drawable2 = getResources().getDrawable(R.drawable.selector_shop);
        Drawable drawable3 = getResources().getDrawable(R.drawable.selector_user);
        drawable.setBounds(bound);
        drawable1.setBounds(bound);
        drawable2.setBounds(bound);
        drawable3.setBounds(bound);
        mMyDeviceRBT.setCompoundDrawables(null, drawable, null, null);
        mBbsRBT.setCompoundDrawables(null, drawable1, null, null);
        mDiscoveryRBT.setCompoundDrawables(null, drawable2, null, null);
        mUserCenterRBT.setCompoundDrawables(null, drawable3, null, null);
        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
        viewPager.setOffscreenPageLimit(4);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(MY_DEVICE);
    }

    private void initLayoutListView() {
        ExpandableLayout wlanLayout = new ExpandableLayout(DeviceType.DEVICE_TYPE_WLAN, false, "智能网关设置", mWlans);
        ExpandableLayout spaceLayout = new ExpandableLayout(DeviceType.DEVICE_TYPE_WLAN, false, "温湿度", mWlans);
        ExpandableLayout remoteLayout = new ExpandableLayout(DeviceType.DEVICE_TYPE_DIY_REMOTE, false, "遥控器", mRemotes);
        ExpandableLayout cameraLayout = new ExpandableLayout(DeviceType.DEVICE_TYPE_SECURITY_CAMERA, false, "摄像头设置", mCameras);
        ExpandableLayout wirelessLayout = new ExpandableLayout(DeviceType.WIRELSEE_SWITCH, false, "无线开关设置", wireless);
        ExpandableLayout switchLayout = new ExpandableLayout(DeviceType.DEVICE_TYPE_SWITCH, false, "智能开关设置", mSwitchs);
        ExpandableLayout curtainLayout = new ExpandableLayout(DeviceType.DEVICE_TYPE_CURTAIN, false, "智能窗帘设置", mCurtain);
        ExpandableLayout socketLayout = new ExpandableLayout(DeviceType.DEVICE_TYPE_SOCKET, false, "智能插座设置", mSockets);
        ExpandableLayout lightLayout = new ExpandableLayout(DeviceType.DEVICE_TYPE_RGB_LIGHT, false, "智能灯光设置", mLights);
        ExpandableLayout lockLayout = new ExpandableLayout(DeviceType.DEVICE_TYPE_LOCK, false, "智能门锁设置", mLocks);

        mLayouts.add(wlanLayout);
        mLayouts.add(spaceLayout);
        mLayouts.add(remoteLayout);
        mLayouts.add(cameraLayout);
        mLayouts.add(wirelessLayout);
        mLayouts.add(switchLayout);
        mLayouts.add(curtainLayout);
        mLayouts.add(socketLayout);
        mLayouts.add(lightLayout);
        mLayouts.add(lockLayout);
        mLayoutAdapter = new LayoutAdapter();
        mLayoutLv.setAdapter(mLayoutAdapter);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.device_rbtn:
                currentPage = MY_DEVICE;
                viewPager.setCurrentItem(MY_DEVICE);
               topBar.setVisibility(View.VISIBLE);
                mBlock.setVisibility(View.VISIBLE);
                tv_statusBar_shop.setVisibility(View.GONE);
                ImmersionBar.with(this).transparentBar() .fitsSystemWindows(false).init();
//			checkShop(); // 检查是否有商城订单
                break;
            case R.id.bbs_rbtn:
                currentPage = BBS;
                viewPager.setCurrentItem(BBS);
                topBar.setVisibility(View.GONE);
                mBlock.setVisibility(View.GONE);
                tv_statusBar_shop.setVisibility(View.GONE);
                break;
            case R.id.discovery_rbtn:
                // 状态栏不沉浸
                currentPage = SHOP;
                viewPager.setCurrentItem(SHOP);
               if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    tv_statusBar_shop.setVisibility(View.GONE);
                   //android4.4以上沉浸式状态栏和导航栏实现以及Bar的其他管理
                   ImmersionBar.with(this)
                           .transparentBar()
                           .statusBarColor(R.color.status_bars)
                           .fitsSystemWindows(true) //使用该属性必须指定状态栏的颜色，不然状态栏透明，
                           .init();
                }
                topBar.setVisibility(View.GONE);
                mBlock.setVisibility(View.GONE);
                break;
            case R.id.usercenter_rbtn:
                currentPage = USERCENTER;
                viewPager.setCurrentItem(USERCENTER);
                tv_statusBar_shop.setVisibility(View.GONE);
                topBar.setVisibility(View.GONE);
                mBlock.setVisibility(View.GONE);
                ImmersionBar.with(this).transparentBar() .fitsSystemWindows(false).init();

                break;
            case R.id.more_layout:
                toggle();
                break;
            case R.id.add_layout:
                Intent intent = new Intent(MainActivity.this, AddTypeSelectionActivity.class);
                startActivity(intent);
                break;
            case R.id.wlan_layout:
                // resetLayout(DeviceType.DEVICE_TYPE_WLAN);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case STARTACTIVITY_SHARE_TARGET_ACTIVITY:
                BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
                    @Override
                    public void onBlurComplete() {
                        Intent intent = new Intent(MainActivity.this, ShareContentActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(intent);
                        finish();
                    }
                });
                break;
            case STARTACTIVITY_SHARE_CONTENT_ACTIVITY:
                BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
                    @Override
                    public void onBlurComplete() {
                        Intent intent = new Intent(MainActivity.this, EnvAuthorActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(intent);
                        finish();
                    }
                });
                break;
            case STARTACTIVITY_ENV_AUTHOR_ACTIVITY:
                BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
                    @Override
                    public void onBlurComplete() {
                        Intent intent = new Intent(MainActivity.this, DeviceAuthorActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(intent);
                        finish();
                    }
                });
                break;
            case STARTACTIVITY_DEVICE_AUTHOR_ACTIVITY:

                break;

            default:
                break;
        }
    }

    private void checkDeviceState(int groupPosition) {
        if (groupPosition == 9) {
            mLocks = DeviceManager.getInstance().getLocks();
            Log.i("wmy", "1611 mLocks.size() = " + mLocks.size());
            if (mLocks.size() == 0) {
                return;
            }
        }
        if (groupPosition == 5) {
            mSwitchs = DeviceManager.getInstance().getSwitchs();
            Log.i("wmy", "1611 mSwitchs.size() = " + mSwitchs.size());
            if (mSwitchs.size() == 0) {
                return;
            }
        } else if (groupPosition == 7) {
            mSockets = DeviceManager.getInstance().getSockets();
            Log.i("wmy", "1611 mSockets.size() = " + mSockets.size());
            if (mSockets.size() == 0) {
                return;
            }
        } else if (groupPosition == 8) {
            Log.i("wmy", "1617 mLights.size() = " + mLights.size());
            mLights = DeviceManager.getInstance().getLights();
            if (mLights.size() == 0) {
                return;
            }
        } else if (groupPosition == 4) {
            Log.i("wmy", "1617 mCurtain.size() = " + mCurtain.size());
             wireless= DeviceManager.getInstance().getWireless();

            if (mCurtain.size() == 0) {
                return;
            }
        } else if (groupPosition == 6) {
            Log.i("wmy", "1617 wireless.size() = " + wireless.size());
            mCurtain = DeviceManager.getInstance().getCurtains();

            if (wireless.size() == 0) {
                return;
            }
        } else if (groupPosition == 3) {
            mCameras = DeviceManager.getInstance().getCameras();
            Log.i("xwy", "1617 mCameras.size() = " + mCameras.size());
            if (mCameras.size() == 0) {
                return;
            }
            Log.i("我的摄像头", "1617 mCameras.size() = " + mCameras.size());
            mFunCameras.clear();
            // Demo，如果是进入设备列表就切换到本地模式,退出时切换回NET模式
            FunSupport.getInstance().setLoginType(FunLoginType.LOGIN_BY_INTENTT);
            FunSupport.getInstance().registerOnFunDeviceListener(onFunDeviceListener);
            FunSupport.getInstance().registerOnFunDeviceOptListener(onFunDeviceOptListener);
//			requestToGetDeviceList();
            //定义一个空的序列号字符串,用来装所有的摄像头序列号，有;号隔开，然后一起查询状态
            String devSNs = "";

            for (int i = 0; i < mCameras.size(); i++) {
                if (devSNs.length() > 0) {
                    devSNs += ";";
                }
                FunSupport.getInstance().addDevice(devSNs);
                devSNs += mCameras.get(i).getDeviceAddress();
                FunSupport.getInstance().requestDeviceStatus(FunDevType.EE_DEV_BOUTIQUEROTOT, mCameras.get(i).getDeviceAddress());
            }
            Log.i("我的摄像头", "devSNs:" + devSNs);
//
//			FunSupport.getInstance().requestAllDeviceStatus();
//
//				d.devSn = mCameras.get(i).getDeviceAddress();
//				d.devName = mCameras.get(i).getDeviceAddress();
//				d.devType = FunDevType.EE_DEV_BOUTIQUEROTOT;
//				d.loginName = "admin";
//				d.loginPsw = "";
//
////                    FunDevice d = new FunDevice();
////                    d.devSn = mLanDeviceList.get(i).getDevSn();
////                    d.devName = mLanDeviceList.get(i).getDevName();
////                    d.devType = FunDevType.EE_DEV_BOUTIQUEROTOT;
////                    d.loginName = "admin";
////                    d.loginPsw = "";
//
//				// Demo，如果是进入设备列表就切换到本地模式,退出时切换回NET模式
//				FunSupport.getInstance().setLoginType(FunLoginType.LOGIN_BY_INTENTT);
//				FunSupport.getInstance().registerOnFunDeviceOptListener(onFunDeviceOptListener);
//				// 添加设备之前都必须先登录一下,以防设备密码错误,也是校验其合法性
//				FunSupport.getInstance().requestDeviceLogin(d);
//			}
        }
        mids.clear();
        //mSVProgressBar.showWithStatus("正在获取设备状态");
        SocketManager.getInstance().setListener();
        SocketManager.getInstance().setNeedToCheck(true);
        CheckStatusUtil.getInstance().mHandler = mHandler;
        CheckStatusUtil.getInstance().check(groupPosition);
        switch (groupPosition) {
            case 0:

                break;
            case 1:

                break;
            case 3:// 安防摄像头
                for (int i = 0; i < mCameras.size(); i++) {
                    mCameras.get(i).checkStatus();
                }
            case 6:// 窗帘
                for (int i = 0; i < mCurtain.size(); i++) {
                    mCurtain.get(i).checkStatus();
                }
                break;
            case 5: // 开关
                for (int i = 0; i < mSwitchs.size(); i++) {
                    mSwitchs.get(i).checkStatus();
                }
                break;
            case 4:// 无线开关
                for (int i = 0; i < wireless.size(); i++) {
                    wireless.get(i).checkStatus();
                }
                break;
            case 7: // 插座
                for (int i = 0; i < mSockets.size(); i++) {
                    mSockets.get(i).checkStatus();
                }
                break;
            case 8:// 灯泡
                for (int i = 0; i < mLights.size(); i++) {
                    mLights.get(i).checkStatus();
                }
                break;
            case 9:// 门锁
                for (int i = 0; i < mLocks.size(); i++) {
                    mLocks.get(i).checkStatus();
                }
                break;

            default:
                break;
        }
    }

    private void showOptionDialog(final Device device, final int type) {
        option = new String[3];
        option[0] = "编辑该设备";
        option[1] = "删除该设备";
        option[2] = "取消";
        mNormalListDialog = new NormalListDialog(MainActivity.this, option, device.getDeviceName());
        mNormalListDialog.title("请选择")//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        mNormalListDialog.setOnOperItemClickL(new OnOperItemClickL() {

            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position1, long id) {
                // TODO Auto-generated method stub
                switch (position1) {
                    case 0:
                        // 弹出编辑框
                        editDevice(device, type);
                        mNormalListDialog.dismiss();
                        break;
                    case 1:
                        // 删除设备
                        deleteDevice(device, type);
                        mNormalListDialog.dismiss();
                        break;
                    case 2:
                        // 生成二维码
                        // Toast.makeText(getApplicationContext(), "暂未实现",
                        // Toast.LENGTH_SHORT).show();
                        mNormalListDialog.dismiss();
                        break;
                    case 3:
                        // 取消
                        mNormalListDialog.dismiss();
                        break;

                    default:
                        break;
                }
            }
        });
    }

    private void showOptionDialog1(final Device device, final int type) {
        option = new String[4];
        option[0] = "编辑该设备";
        option[1] = "删除该设备";
        option[2] = "设备升级";
        option[3] = "取消";
        if (SocketManager.getInstance().sMap.get(device.getDeviceID()) != null) {
            harddeviceversion = SocketManager.getInstance().sMap.get(device.getDeviceID()).getVersion();
        } else {
            harddeviceversion = getString(R.string.can_not_get_version);
        }
        mNormalListDialog = new NormalListDialog(MainActivity.this, option, device.getDeviceName(), harddeviceversion);
        mNormalListDialog.title("请选择")//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        mNormalListDialog.setOnOperItemClickL(new OnOperItemClickL() {

            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position1, long id) {
                // TODO Auto-generated method stub
                switch (position1) {
                    case 0:
                        // 弹出编辑框
                        editDevice(device, type);
                        mNormalListDialog.dismiss();
                        break;
                    case 1:
                        // 删除设备
                        deleteDevice(device, type);
                        mNormalListDialog.dismiss();
                        break;
                    case 2:
                        // 设备升级
                        int vcode = Util.getVersionCode(harddeviceversion);
                        if (vcode < SocketManager.getInstance().hardDeviceversionCode) {
                            updateDevice(device);
                            mNormalListDialog.dismiss();
                        } else {
                            ToastShow.Show(getApplicationContext(), "当前硬件已是最新版，无需升级");
                        }

                        break;
                    case 3:
                        // 取消
                        mNormalListDialog.dismiss();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * 升级设备 弹出进度框 发送升级命令 接收升级进度回调 根据进度更新进度条 升级完毕显示升级成功
     */
    private void updateDevice(final Device device) {
        MySocket socket = SocketManager.getInstance().sMap.get(device.getDeviceID());
        if (socket == null) {
            ToastShow.Show(getApplicationContext(), "无法升级,该网关不存在");
            return;
        } else if (!socket.isLocalSuccess()) {
            ToastShow.Show(getApplicationContext(), "无法连接该网关");
            return;
        } else {
            // socket.update();
            socket.forceUpdate();
            dialog = new Dialog(MainActivity.this, R.style.MyDialogStyle);
            dialog.setContentView(R.layout.dialog_device_update);
            mDeviceNameT = (TextView) dialog.findViewById(R.id.name_tv1);
            mDeviceNameT.setText(device.getDeviceName());
            mPercentT = (TextView) dialog.findViewById(R.id.percent_tv);
            mPerventImg = (ImageView) dialog.findViewById(R.id.percent_img);
            dialog.show();
            socket.setRecDataCallBackListener_Update(new RecDataCallBackListener_Update() {

                @Override
                public void onReceiveData(String data) {
                    // TODO Auto-generated method stub
                    Message msg = Message.obtain();
                    msg.what = GET_UPDATE_PROGRESS;
                    msg.obj = data;
                    mHandler.sendMessage(msg);
                }
            });
        }
    }

    private void editDevice(final Device device, final int type) {
        mEditNameDialog = new EditDeviceNameDialog(MainActivity.this);
        mEditNameDialog.setDeviceName(device.getDeviceName());
        mEditNameDialog.setOnCancelOptionListener(new EditDeviceNameDialog.OnCancelOptionListener() {

            @Override
            public void cancel() {
                mEditNameDialog.dismiss();
            }
        });
        mEditNameDialog.setOnEnsureOptionListener(new EditDeviceNameDialog.OnEnsureOptionListener() {

            @Override
            public void ensure(String name) {
                boolean e = DeviceManager.getInstance().checkName(name);
                if (e) {
                    ToastShow.Show(getApplicationContext(), getString(R.string.device_exists1));
                    return;
                }
                if (name.isEmpty() || name.length() < 2 || name.length() > 10) {
                    ToastShow.Show(getApplicationContext(), getString(R.string.device_name_not_vaild));
                } else {
                    mEditNameDialog.dismiss();
                    updateName(name, device, type);
                }
            }
        });
        mEditNameDialog.show();
    }

    private void updateName(final String name, final Device device, final int type) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                RequestParams params = new RequestParams(HttpURL.UPDATE_DEVICE_URL);
                params.setAsJsonContent(true);
                JSONObject obj = new JSONObject();
                try {
                    obj.put("deviceName", name);
                    obj.put("deviceId", device.getDeviceID());
                    obj.put("key", "10000");
                    obj.put("requestTime", "" + System.currentTimeMillis());
                    obj.put("token", (String) SPUtils.get(MainActivity.this, "token", ""));
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                params.setBodyContent(obj.toString());
                x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        // Log.e("wmy", "修改名字 = " + result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String value = jsonObject.getString("resultCode");
                            if (value.equals("1")) {
                                // 更新DeviceManager中设备哈希表的名字
                                // DeviceManager.getInstance().upDateDeviceName(device);
                                Message msg = Message.obtain();
                                msg.what = EDIT_DEVICE_NAME_SUCCESS;
                                msg.arg1 = type;
                                mHandler.sendMessage(msg);
                            } else {
                                Message msg = Message.obtain();
                                msg.what = EDIT_DEVICE_NAME_FAIL;
                                mHandler.sendMessage(msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCancelled(CancelledException arg0) {

                    }

                    @Override
                    public void onError(Throwable arg0, boolean arg1) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        }).start();
    }

    private void deleteDevice(final Device device, final int type) {
        final String deviceId = device.getDeviceID();
        mNormalDialog = new NormalDialog(MainActivity.this);
        mNormalDialog.content("是否删除该设备：" + device.getDeviceName() + "？").style(NormalDialog.STYLE_TWO)//
                .titleTextSize(18)//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                mNormalDialog.dismiss();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                mNormalDialog.dismiss();
                String deviceID = device.getDeviceID();
                if (deviceID.equals("")) {
                    deleteLocal();
                    SocketManager.getInstance().sMap.remove(device.getDeviceID());
                } else {
                    if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
                        ToastShow.Show(getApplicationContext(), "没有网络");
                        return;
                    }
                    mSVProgressBar.showWithStatus("正在删除");
                    RequestParams params = new RequestParams(HttpURL.DELETE_DEVICE_URL);
                    params.setAsJsonContent(true);
                    JSONObject obj = new JSONObject();
                    try {
                        obj.put("deviceId", device.getDeviceID());
                        obj.put("key", "10000");
                        obj.put("requestTime", "" + System.currentTimeMillis());
                        obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                        Log.d("Tag", "delete device " + obj.toString());
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    params.setBodyContent(obj.toString());
                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {
                            Log.e("test", "delete =" + result);
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String resultCode = jsonObject.getString("resultCode");
                                if (resultCode.equals("1")) {
                                    deleteLocal();
                                    ToastShow.Show(getApplicationContext(), "删除成功");
                                    getAllDevice();
                                } else {
                                    getAllDevice();
                                    throw new Exception();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                // ToastShow.Show(getApplicationContext(),
                                // "删除失败，请稍后再试");
                                getAllDevice();
                            }
                        }

                        @Override
                        public void onCancelled(CancelledException arg0) {

                        }

                        @Override
                        public void onError(Throwable arg0, boolean arg1) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                }
            }

            private void deleteLocal() {
                DeviceManager.getInstance().deleteDevice(device);
                if (SocketManager.getInstance().sMap.get(deviceId) != null) {
                    SocketManager.getInstance().sMap.get(deviceId).stopLocalTcpClient();
                    SocketManager.getInstance().sMap.remove(deviceId);
                }
                initData();
            }

        });
    }

    private void onOrOff(int p, boolean b, int type) {
        if (b) {
            switch (type) {

                case DeviceType.DEVICE_TYPE_SOCKET:
                    d = mLayouts.get(7).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_RGB_LIGHT:
                    d = mLayouts.get(8).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_LOCK:
                    d = mLayouts.get(9).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_SECURITY_CAMERA:
                    d = mLayouts.get(3).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_CURTAIN:
                    d = mLayouts.get(4).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_SWITCH:
                    if (mLayouts.get(5).getDevices().size() > p) {
                        d = mLayouts.get(5).getDevices().get(p);
                    }
                    break;
                default:
                    break;
            }
            DeviceManager.getInstance().setDeviceState(d.getDeviceID(), true);
            if (SocketManager.getInstance().sMap.get(d.getMainDeviceId()) != null) {
                if (SocketManager.getInstance().sMap.get(d.getMainDeviceId()).isLocalSuccess()) {
                    SocketManager.getInstance().sMap.get(d.getMainDeviceId()).sendMqttData(d.getOpenCmd());
                } else {
                    SocketManager.getInstance().sendRemoteData(
                            SocketManager.getInstance().sMap.get(d.getMainDeviceId()).getMac(), d.getMainDeviceId(),
                            d.getOpenCmd());
                }
            }
        } else {
            switch (type) {
                case DeviceType.DEVICE_TYPE_SWITCH:
                    d = mLayouts.get(5).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_SOCKET:
                    d = mLayouts.get(7).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_RGB_LIGHT:
                    d = mLayouts.get(8).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_LOCK:
                    d = mLayouts.get(9).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_SECURITY_CAMERA:
                    d = mLayouts.get(3).getDevices().get(p);
                    break;
                case DeviceType.DEVICE_TYPE_CURTAIN:
                    d = mLayouts.get(4).getDevices().get(p);
                    break;
                default:
                    break;
            }
            // 发送指令
            // 改变状态
            DeviceManager.getInstance().setDeviceState(d.getDeviceID(), false);
            if (SocketManager.getInstance().sMap.get(d.getMainDeviceId()) != null) {
                if (SocketManager.getInstance().sMap.get(d.getMainDeviceId()).isLocalSuccess()) {
                    SocketManager.getInstance().sMap.get(d.getMainDeviceId()).sendMqttData(d.getCloseCmd());
                } else {
                    SocketManager.getInstance().sendRemoteData(
                            SocketManager.getInstance().sMap.get(d.getMainDeviceId()).getMac(), d.getMainDeviceId(),
                            d.getCloseCmd());
                }
            }
        }

    }

    private void onOrOff1(int pos, boolean b) {
        if (b) {//全开
            List<Device> deviceList = mLayouts.get(pos).getDevices();
            for (Device dd: deviceList) {
                DeviceManager.getInstance().setDeviceState(dd.getDeviceID(), true);
                if (SocketManager.getInstance().sMap.get(dd.getMainDeviceId()) != null) {
                    if (SocketManager.getInstance().sMap.get(dd.getMainDeviceId()).isLocalSuccess()) {
                        SocketManager.getInstance().sMap.get(dd.getMainDeviceId()).sendMqttData(dd.getOpenCmd());
                        String opencmd=dd.getOpenCmd();
                        Log.e("opencmd=","xxx "+opencmd);
                    } else {
                        SocketManager.getInstance().sendRemoteData(
                                SocketManager.getInstance().sMap.get(dd.getMainDeviceId()).getMac(), dd.getMainDeviceId(),
                                dd.getOpenCmd());
                    }
                }
            }


        } else {//全关
            List<Device> deviceList = mLayouts.get(pos).getDevices();
            for (Device dd: deviceList) {
                // 改变状态
                DeviceManager.getInstance().setDeviceState(dd.getDeviceID(), false);
                if (SocketManager.getInstance().sMap.get(dd.getMainDeviceId()) != null) {
                    if (SocketManager.getInstance().sMap.get(dd.getMainDeviceId()).isLocalSuccess()) {
                        SocketManager.getInstance().sMap.get(dd.getMainDeviceId()).sendMqttData(dd.getCloseCmd());
                    } else {
                        SocketManager.getInstance().sendRemoteData(
                                SocketManager.getInstance().sMap.get(dd.getMainDeviceId()).getMac(), dd.getMainDeviceId(),
                                dd.getCloseCmd());
                    }
                }
            }
            }


    }

//	private void checkShop() {
//		RequestParams params = new RequestParams("http://api.shop.soochowlightpower.com/v2/xin.order.list");
//		params.addHeader("X-ECAPI-Authorization", (String) SPUtils.get(getApplicationContext(), "shopToken", ""));
//		Log.i("wmy", "shopToken = " + (String) SPUtils.get(getApplicationContext(), "shopToken", ""));
//		params.setAsJsonContent(true);
//		JSONObject obj = new JSONObject();
//		try {
//			obj.put("status", 0);
//			obj.put("per_page", 10);
//			obj.put("page", 1);
//			Log.e("wmy",
//					" get all dingdan = " + obj.toString() + " " + params.getHeaders().get("X-ECAPI-Authorization"));
//		} catch (JSONException e1) {
//			e1.printStackTrace();
//		}
//		params.setBodyContent(obj.toString());
//		x.http().post(params, new Callback.CommonCallback<String>() {
//			@Override
//			public void onSuccess(String result) {
//				Log.e("wmy", "get all dingdan=" + result);
//				JSONObject jsonObject;
//				try {
//					jsonObject = new JSONObject(result);
//					JSONObject jo = jsonObject.getJSONObject("data");
//					JSONArray ja = jo.getJSONArray("orders");
//					if (ja.length() > 0) {
//						Log.i("wmy", "有订单存在，可以发布工单");
//						MainFragment.instance.hasOrder = true;
//					}
//				} catch (JSONException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//
//			@Override
//			public void onCancelled(CancelledException arg0) {
//				Log.e("wmy", "get all dingdan cancel");
//			}
//
//			@Override
//			public void onError(Throwable arg0, boolean arg1) {
//				// lt.error();
//				Log.e("wmy", "get all dingdan error");
//			}
//
//			@Override
//			public void onFinished() {
//				Log.e("wmy", "get all dingdan finish");
//			}
//		});
//
//	}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // if (!slidingMenuShowing) {
            // Log.i("wmy", "没有打开");
            exit();
            return false;
            // } else {
            // Log.i("wmy", "打开");
            // if(mSVProgressBar.isShowing()){
            // mSVProgressBar.dismiss();
            // }
            // return false;
            // }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast toast = Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT);
            toast.show();
            exitTime = System.currentTimeMillis();
        } else {
            DeviceManager.getInstance().clearDevice();
            DeviceManager.getInstance().clearHouse();
            DeviceManager.getInstance().clearRoom();
            finish();
            System.exit(0);
        }
    }


    public interface OnDataUpdateListener {
        public void update(int count1, int count2);
    }

    public void setDataUpdateLiistener(OnDataUpdateListener onDataUpdateListener) {
        this.onDataUpdateListener = onDataUpdateListener;
    }

    public void initListener() {
        SocketManager.getInstance().setL(new OrderListener() {

            @Override
            public void onShow(String msg) {
                // TODO Auto-generated method stub
                if (needNoticeSetup) {
                    needNoticeSetup = false;
                    Message m = Message.obtain();
                    m.what = 7;
                    m.obj = msg;
                    mHandler.sendMessage(m);
                }
            }
        });
    }

    class LayoutAdapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            // TODO Auto-generated method stub
            return mLayouts.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            // TODO Auto-generated method stub
            return mLayouts.get(groupPosition).getDevices().size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            // TODO Auto-generated method stub
            return mLayouts.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getGroupId(int groupPosition) {
            // TODO Auto-generated method stub
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public View getGroupView(final int groupPosition,  boolean isExpanded, View view, ViewGroup parent) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.item_layout, null);
            holdView= new HoldView();
            holdView.typeImg = (ImageView) view.findViewById(R.id.layout_type);
            holdView.typeName = (TextView) view.findViewById(R.id.name_tv);
            holdView.biao = (ImageView) view.findViewById(R.id.biao);
            holdView.mToggleButton = (ToggleButton) view.findViewById(R.id.onoff_tgl);
            view.setTag(R.layout.item_layout, groupPosition);
            view.setTag(R.layout.item_main_device, -1);
            view.setTag(holdView);
            ExpandableLayout el = mLayouts.get(groupPosition);

            switch (el.getType()) {
                case DeviceType.DEVICE_TYPE_WLAN:
                    holdView.typeImg.setImageResource(R.drawable.btn_100);
                    holdView.mToggleButton.setVisibility(View.INVISIBLE);
                    break;
                case DeviceType.DEVICE_TYPE_SWITCH:
                    holdView.typeImg.setImageResource(R.drawable.btn106);
                    holdView.mToggleButton.setVisibility(View.VISIBLE);
                    holdView.mToggleButton.setChecked(mLayouts.get(groupPosition).getChecked());
                    break;
                case DeviceType.DEVICE_TYPE_SOCKET:
                    holdView.typeImg.setImageResource(R.drawable.btn107);
                    holdView.mToggleButton.setVisibility(View.VISIBLE);
                    holdView.mToggleButton.setChecked(mLayouts.get(groupPosition).getChecked());
                    break;
                case DeviceType.DEVICE_TYPE_DIY_REMOTE:
                    holdView.typeImg.setImageResource(R.drawable.btn101);
                    holdView.mToggleButton.setVisibility(View.INVISIBLE);
                    break;
                case DeviceType.DEVICE_TYPE_LOCK:
                    holdView.typeImg.setImageResource(R.drawable.btn103);
                    holdView.mToggleButton.setVisibility(View.VISIBLE);
                    holdView.mToggleButton.setChecked(mLayouts.get(groupPosition).getChecked());
                    break;
                case DeviceType.DEVICE_TYPE_RGB_LIGHT:
                    holdView.typeImg.setImageResource(R.drawable.btn105);
                    holdView.mToggleButton.setVisibility(View.VISIBLE);
                    holdView.mToggleButton.setChecked(mLayouts.get(groupPosition).getChecked());
                    break;
                case DeviceType.DEVICE_TYPE_SECURITY_CAMERA:
                    holdView.typeImg.setImageResource(R.drawable.icon_camera);
                    holdView.mToggleButton.setVisibility(View.INVISIBLE);
                    break;
                case DeviceType.DEVICE_TYPE_CURTAIN:
                    holdView.typeImg.setImageResource(R.drawable.ic_curtain);
                    holdView.mToggleButton.setVisibility(View.VISIBLE);
                    holdView.mToggleButton.setChecked(mLayouts.get(groupPosition).getChecked());
                    Log.e("checkstatus",mLayouts.get(groupPosition).getChecked()+"");
                    break;
                case DeviceType.WIRELSEE_SWITCH:
                    holdView.typeImg.setImageResource(R.drawable.btn106);
                    holdView.mToggleButton.setVisibility(View.INVISIBLE);
                    break;
                default:
                    break;
            }

         //   holdView.mToggleButton.setOnClickListener(new Group_CheckBox_Click(groupPosition,holdView));
            holdView.mToggleButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    flag=mLayouts.get(groupPosition).getChecked();
                    mLayouts.get(groupPosition).setChecked(!flag);
                    //  holdView.mToggleButton.setChecked(!flag);
                //    mLayouts.get(groupPosition).setChecked(!flag);

                    //  boolean groupIsChecked = !mLayouts.get(groupPosition).getChecked();
                    Message msg = Message.obtain();
                    msg.what = MainActivity.SINGLE_DEVICE_CTRL1;
                    msg.arg1 = groupPosition;
                    //   msg.arg2 = d.getDeviceType();
                    msg.obj =!flag;
                    mHandler.sendMessage(msg);
                }
            });

            if (groupPosition == 1) {
                holdView.typeImg.setImageResource(R.drawable.wenshidu);
            }
            holdView.typeName.setText(el.getName());
            if (isExpanded) {
                holdView.biao.setImageResource(R.drawable.biao2);
            } else {
                holdView.biao.setImageResource(R.drawable.biao1);
            }

            return view;
        }


        class Group_CheckBox_Click implements View.OnClickListener {
            private int groupPosition;
            private HoldView groupHolder;


            Group_CheckBox_Click(int groupPosition,HoldView groupHolder) {
                this.groupPosition = groupPosition;
                this.groupHolder = groupHolder;
            }

            public void onClick(View v) {
                groupHolder.mToggleButton.setChecked(!mLayouts.get(groupPosition).getChecked());
               // mLayouts.get(groupPosition).toggle();
              //  int childrenCount = mLayouts.get(groupPosition).getChildCount();
                boolean groupIsChecked = !mLayouts.get(groupPosition).getChecked();
               /* for (int i = 0; i < childrenCount; i++) {
                    mLayouts.get(groupPosition).getChild(i).setIsCheck(groupIsChecked);
                }*/
                Message msg = Message.obtain();
                msg.what = MainActivity.SINGLE_DEVICE_CTRL1;
                msg.arg1 = groupPosition;
                //   msg.arg2 = d.getDeviceType();
                msg.obj = groupIsChecked;
                mHandler.sendMessage(msg);
               // notifyDataSetChanged();
            }
        }


        @Override
        public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View view,
                                 ViewGroup parent) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.item_main_device, null);
            childHoldView = new ChildHoldView();
            childHoldView.deviceTv = (TextView) view.findViewById(R.id.name_tv);
            childHoldView.mToggleButton = (ToggleButton) view.findViewById(R.id.onoff_tgl);
            childHoldView.mToggleL = (LinearLayout) view.findViewById(R.id.toggle_l);
            childHoldView.state = (TextView) view.findViewById(R.id.state_tv);
            childHoldView.wenshidu_layout = (LinearLayout) view.findViewById(R.id.wenshidu_layout);
            // childHoldView.wendu_tv = (TextView)
            // view.findViewById(R.id.wendu);
            childHoldView.shidu_tv = (TextView) view.findViewById(R.id.shidu);
            view.setTag(R.layout.item_layout, groupPosition);
            view.setTag(R.layout.item_main_device, childPosition);
            view.setTag(childHoldView);
            if (childPosition < mLayouts.get(groupPosition).getDevices().size()) {
                final Device d = mLayouts.get(groupPosition).getDevices().get(childPosition);
                if (groupPosition != 1) {
                    if (mLayouts.size() > groupPosition
                            && mLayouts.get(groupPosition).getDevices().size() > childPosition) {
                        childHoldView.deviceTv.setText(d.getDeviceName());
                        if (d.getDeviceType() == DeviceType.DEVICE_TYPE_RGB_LIGHT
                                || d.getDeviceType() == DeviceType.DEVICE_TYPE_RGB_TIAO
                                || d.getDeviceType() == DeviceType.DEVICE_TYPE_SOCKET
                                || d.getDeviceType() == DeviceType.DEVICE_TYPE_SW_LIGHT
                                || d.getDeviceType() == DeviceType.DEVICE_TYPE_SWITCH
                                || d.getDeviceType() == DeviceType.DEVICE_TYPE_CHAZUO
//								|| d.getDeviceType() == DeviceType.DEVICE_TYPE_SECURITY_CAMERA
                                || d.getDeviceType() == DeviceType.DEVICE_TYPE_CURTAIN) {
                            childHoldView.mToggleButton.setVisibility(View.GONE);
                            childHoldView.mToggleL.setClickable(true);
                        } else {
                            childHoldView.mToggleL.setVisibility(View.GONE);
                        }
                        //如果类型是摄像头，则不让他点击
                        if (d.getDeviceType() == DeviceType.DEVICE_TYPE_SECURITY_CAMERA) {
                            childHoldView.mToggleButton.setClickable(false);
                        }
                        if (d.getDeviceType() == DeviceType.DEVICE_TYPE_WLAN) {
                            MySocket socket = SocketManager.getInstance().sMap.get(d.getDeviceID());

                            if (socket != null) {
                                if (socket.isLocalSuccess()) {
                                    childHoldView.state.setText("本地");
                                } else if (!socket.isLocalSuccess() && SocketManager.getInstance().isRemoteSuccess()) {

                                    if (SocketManager.getInstance().mStatusMap.get(d.getDeviceID()) != null) {
                                        if (SocketManager.getInstance().mStatusMap.get(d.getDeviceID()) == 1) {
                                            childHoldView.state.setText("远程");
                                        } else {
                                            childHoldView.state.setText("未连接");
                                        }
                                    } else {
                                        childHoldView.state.setText("未连接");
                                    }
                                } else {
                                    childHoldView.state.setText("未连接");
                                }
                            }
                        }
                        childHoldView.mToggleL.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View arg0) {
                                // TODO Auto-generated method stub
                                Log.i("wmy", "消费点击");
                            }
                        });
                        if (DeviceManager.getInstance().checkDeviceState(d.getDeviceID())) {
                            childHoldView.mToggleButton.setChecked(true);
                        } else {
                            childHoldView.mToggleButton.setChecked(false);
                        }

                        //如果是摄像头类型的
                        if (d.getDeviceType() == DeviceType.DEVICE_TYPE_SECURITY_CAMERA) {
                            //设置摄像头的状态
                            if (mFunCameras.size() > childPosition && mCameras.size() > childPosition) {
                                for (int i = 0; i < mFunCameras.size(); i++) {
                                    if (mFunCameras.get(i).getDevSn().equals(mCameras.get(childPosition).getDeviceAddress())) {
                                      //  childHoldView.mToggleButton.setChecked(mFunCameras.get(i).devStatus == FunDevStatus.STATUS_ONLINE ? true : false);
                                    }
                                }
                            }
                        }

                        childHoldView.mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                            @Override
                            public void onCheckedChanged(CompoundButton arg0, boolean isCheck) {
                                Message msg = Message.obtain();
                                msg.what = MainActivity.SINGLE_DEVICE_CTRL;
                                msg.arg1 = childPosition;
                                msg.arg2 = d.getDeviceType();
                                msg.obj = isCheck;
                                mHandler.sendMessage(msg);
                            }
                        });
                        view.setOnTouchListener(new OnTouchListener() {

                            @Override
                            public boolean onTouch(View v, MotionEvent e) {
                                // TODO Auto-generated method stub
                                switch (e.getAction()) {
                                    case MotionEvent.ACTION_DOWN:
                                        // Log.i("wmy", "按下e.getX() = " + e.getX() +
                                        // "
                                        // e.getY() = " + e.getY());

                                        break;
                                    case MotionEvent.ACTION_UP:
                                        // Log.i("wmy", "抬起e.getX() = " + e.getX() +
                                        // "
                                        // e.getY() = " + e.getY());
                                        break;

                                    default:
                                        break;
                                }
                                return false;
                            }
                        });
                    }
                } else if (groupPosition == 1) {
                    childHoldView.mToggleL.setVisibility(View.GONE);
                    childHoldView.wenshidu_layout.setVisibility(View.VISIBLE);
                    if (d != null) {
                        MySocket socket = SocketManager.getInstance().sMap.get(d.getDeviceID());
                        if (socket != null) {
                            // childHoldView.wendu_tv.setText("温度：" +
                            // socket.getTemp() + "℃");
                            childHoldView.shidu_tv.setText("温/湿度：" + socket.getTemp() + "℃/" + socket.getHumity());
                            childHoldView.deviceTv.setText(d.getDeviceName());
                            childHoldView.state.setVisibility(View.GONE);
                        }
                    }
                }
            }
            return view;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return true;
        }

        HoldView holdView;
        ChildHoldView childHoldView;

        class HoldView {
            ImageView typeImg;
            TextView typeName;
            ImageView biao;
            ToggleButton mToggleButton;
        }

        class ChildHoldView {
            TextView deviceTv;
            ToggleButton mToggleButton;
            LinearLayout mToggleL;
            TextView state;
            LinearLayout wenshidu_layout;
            // TextView wendu_tv;
            TextView shidu_tv;
        }

    }
    //////////////////////////////////////////////////

    private DialogWaitting mWaitDialog = null;

    public void showWaitDialog() {
        if (null == mWaitDialog) {
            mWaitDialog = new DialogWaitting(this);
        }
        mWaitDialog.show();
    }

    public void hideWaitDialog() {
        if (null != mWaitDialog) {
            mWaitDialog.dismiss();
        }
    }

    private void requestToGetLanDeviceList() {
        if (!FunSupport.getInstance().requestLanDeviceList()) {
            Toast.makeText(getApplicationContext(), R.string.guide_message_error_call, Toast.LENGTH_LONG);
        } else {
            showWaitDialog();
        }
    }

    private void requestToGetDeviceList() {
        if (!FunSupport.getInstance().requestDeviceList()) {
            Toast.makeText(getApplicationContext(), R.string.guide_message_error_call, Toast.LENGTH_LONG);
        } else {
//			showWaitDialog();
        }
    }

    private OnFunDeviceOptListener onFunDeviceOptListener = new OnFunDeviceOptListener() {
        @Override
        public void onDeviceLoginSuccess(FunDevice funDevice) {
            mFunCameras.add(funDevice);
            Log.i("我的摄像头", "onDeviceLoginSuccess" + funDevice.devSn + "---" + funDevice.getId());
        }

        @Override
        public void onDeviceLoginFailed(FunDevice funDevice, Integer errCode) {
            Log.i("我的摄像头", "onDeviceLoginFailed" + funDevice.devSn + "---" + funDevice.devMac);
        }

        @Override
        public void onDeviceGetConfigSuccess(FunDevice funDevice, String configName, int nSeq) {
            Log.i("我的摄像头", "onDeviceGetConfigSuccess");
        }

        @Override
        public void onDeviceGetConfigFailed(FunDevice funDevice, Integer errCode) {
            Log.i("我的摄像头", "onDeviceGetConfigFailed");
        }

        @Override
        public void onDeviceSetConfigSuccess(FunDevice funDevice, String configName) {
            Log.i("我的摄像头", "onDeviceSetConfigSuccess");
        }

        @Override
        public void onDeviceSetConfigFailed(FunDevice funDevice, String configName, Integer errCode) {
            Log.i("我的摄像头", "onDeviceSetConfigFailed");
        }

        @Override
        public void onDeviceChangeInfoSuccess(FunDevice funDevice) {
            Log.i("我的摄像头", "onDeviceChangeInfoSuccess");
        }

        @Override
        public void onDeviceChangeInfoFailed(FunDevice funDevice, Integer errCode) {
            Log.i("我的摄像头", "onDeviceChangeInfoFailed");
        }

        @Override
        public void onDeviceOptionSuccess(FunDevice funDevice, String option) {
            Log.i("我的摄像头", "onDeviceOptionSuccess");
        }

        @Override
        public void onDeviceOptionFailed(FunDevice funDevice, String option, Integer errCode) {
            Log.i("我的摄像头", "onDeviceOptionFailed");
        }

        @Override
        public void onDeviceFileListChanged(FunDevice funDevice) {
            Log.i("我的摄像头", "onDeviceFileListChanged");
        }

        @Override
        public void onDeviceFileListChanged(FunDevice funDevice, H264_DVR_FILE_DATA[] datas) {
            Log.i("我的摄像头", "onDeviceFileListChanged");
        }

        @Override
        public void onDeviceFileListGetFailed(FunDevice funDevice) {
            Log.i("我的摄像头", "onDeviceFileListGetFailed");
        }
    };

    private OnFunDeviceListener onFunDeviceListener = new OnFunDeviceListener() {
        @Override
        public void onDeviceListChanged() {
            Log.i("登陆有数据了", "" + FunSupport.getInstance().getDeviceList().size());
            if (FunSupport.getInstance().getDeviceList().size() > 0) {
                Log.i("登陆有数据了222", "" + FunSupport.getInstance().getDeviceList().get(0).devSn + "---" + FunSupport.getInstance().getDeviceList().get(0).devMac + "---" + FunSupport.getInstance().getDeviceList().get(0).devStatus);
            }

        }

        @Override
        public void onDeviceStatusChanged(FunDevice funDevice) {
            mFunCameras.add(funDevice);
            mLayoutAdapter.notifyDataSetChanged();
            Log.i("登陆有数据了", "onDeviceStatusChanged" + funDevice.devStatus + "---" + funDevice.getId() + "---" + funDevice.getDevSn());
        }

        @Override
        public void onDeviceAddedSuccess() {
            Log.i("登陆有数据了", "onDeviceAddedSuccess");
        }

        @Override
        public void onDeviceAddedFailed(Integer errCode) {
            Log.i("登陆有数据了", "onDeviceAddedFailed");
        }

        @Override
        public void onDeviceRemovedSuccess() {
            Log.i("登陆有数据了", "onDeviceRemovedSuccess");
        }

        @Override
        public void onDeviceRemovedFailed(Integer errCode) {
            Log.i("登陆有数据了", "onDeviceRemovedFailed");
        }

        @Override
        public void onAPDeviceListChanged() {
            Log.i("登陆有数据了", "onAPDeviceListChanged");
        }

        @Override
        public void onLanDeviceListChanged() {
            Log.i("登陆有数据了", "onLanDeviceListChanged");
        }
    };
}
